package com.example.mysharding.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zhang Kai(zhangkai32@baidu.com)
 * @version 1.0.0
 * @ClassName JsonUtils.java
 * @Description TODO
 * @createTime 2021/03/17.
 */
@Slf4j
public class JsonUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();


    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    public static <T> String obj2Str(T object) {
        if (object == null) {
            return null;
        }
        try {
            return MAPPER.writeValueAsString(object);
        } catch (IOException e) {
            return null;
        }
    }


    public static <T> T str2Obj(String str, Class<T> cls) {
        try {
            return MAPPER.readValue(str, cls);
        } catch (Exception e) {
            log.warn("read json fail", e);
            return null;
        }
    }

    public static <T> byte[] obj2Bytes(T object) {
        try {
            return MAPPER.writeValueAsBytes(object);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> List<T> str2List(String str, Class<T> clazz) {
        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(ArrayList.class, clazz);
            return MAPPER.readValue(str, javaType);
        } catch (IOException e) {
            return null;
        }
    }

    public static <K, V> Map<K, V> str2Map(String str, Class<K> keyClass, Class<V> valueClass) {

        if (StringUtils.isEmpty(str)) {
            return Collections.emptyMap();
        }

        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(HashMap.class, keyClass, valueClass);
            return MAPPER.readValue(str, javaType);
        } catch (Throwable e) {
            log.error("JSONUTILS_STR2MAP_ERROR, param={}", str, e);
            return Collections.emptyMap();
        }
    }
    public static <T> ArrayList<HashMap<String, Object>> tradeInfo(String trade1, String trade2, String trade3, String trade4) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        if (StringUtils.isNotBlank(trade1)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("feature_level", 1);
            map.put("feature_name", trade1);
            list.add(map);
        }
        if (StringUtils.isNotBlank(trade2)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("feature_level", 2);
            map.put("feature_name", trade2);
            list.add(map);
        }
        if (StringUtils.isNotBlank(trade3)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("feature_level", 3);
            map.put("feature_name", trade3);
            list.add(map);
        }
        if (StringUtils.isNotBlank(trade4)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("feature_level", 4);
            map.put("feature_name", trade4);
            list.add(map);
        }

        return list;
    }

    public static ObjectMapper getMapper() {

        return MAPPER;
    }
    public static ObjectNode toObjNode(JsonNode node) {
        return (ObjectNode) node;
    }
    public static ArrayNode toArrayNode(JsonNode node) {
        return (ArrayNode) node;
    }


    public static void main(String[] args) throws JsonProcessingException {
        String str1 = "{\"mediaLeadId\":\"240606393219783535\",\"mediaCreateTime\":\"2024-06-06 16:47:42\",\"landingPageUrl\":\"https://preview-sjh.baidu.com/site/wjzw48pe/1bec01ab-27c3-4044-ada2-32b04a49c29a?rs=1799306071&ruk=ZDrz3M4WyQXBGm4WqL_YQw&showpageinpc=1&time=1717663288647\",\"planId\":\"2\",\"unitId\":\"2\",\"creativeId\":\"0\",\"customerName\":\"testtest\",\"customerMobile\":\"15588763568\",\"customerProvinceCode\":\"北京市\",\"customerCityCode\":\"北京市\",\"dealerCode\":\"大众安徽汽车销售服务有限公司C\",\"mediaLeadType\":\"2\",\"encryptFlag\":0,\"channelkey\":\"160729662\",\"channelName\":\"1\",\"extendInfo\":{\"ucid\":\"54392815\"}}";

        String additionalContent = "[\n" +
                "  {\n" +
                "    \"contentKey\": \"所在城市\",\n" +
                "    \"contentValue\": \"武汉\",\n" +
                "    \"url\": \"\"\n" +
                "  },\n" +
                "  {\n" +
                "    \"contentKey\": \"联系方式\",\n" +
                "    \"contentValue\": \"13971858922\",\n" +
                "    \"url\": \"\"\n" +
                "  },\n" +
                "    {\n" +
                "    \"contentKey\": \"姓名\",\n" +
                "    \"contentValue\": \"王子晗\",\n" +
                "    \"url\": \"\"\n" +
                "  }\n" +
                "]";

//        String requestBody = "{\n" +
//                "  \"url\": {\n" +
//                "    \"host_port\": \"https://prod-api.faw.cn/JT/SA/SA-0405/003/DEFAULT/input\",\n" +
//                "    \"query_list\": [\n" +
//                "      \n" +
//                "    ]\n" +
//                "  },\n" +
//                "  \"header\": [],\n" +
//                "  \"method\": \"post\",\n" +
//                "  \"body_format\": \"json\",\n" +
//                "  \"body_ref\": [],\n" +
//                "  \"body\": {\n" +
//                "    \"leads\": [\n" +
//                "      {\n" +
//                "        \"ucid\": \"ucid\",\n" +
//                "        \"id\": \"id\",\n" +
//                "        \"commitTime\": \"commitTime\",\n" +
//                "        \"name\": \"name\",\n" +
//                "        \"phone\": \"phone\",\n" +
//                "        \"dealerId\": \"dealerId\",\n" +
//                "        \"dealerName\": \"dealerName\",\n" +
//                "        \"vfrom1\": \"vfrom1\",\n" +
//                "        \"vfrom2\": \"vfrom2\",\n" +
//                "        \"vfrom3\": \"vfrom3\",\n" +
//                "        \"vfrom4\": \"vfrom4\",\n" +
//                "        \"createTime\": \"createTime\",\n" +
//                "        \"sex\": \"sex\",\n" +
//                "        \"provinceName\": \"provinceName\",\n" +
//                "        \"cityName\": \"cityName\",\n" +
//                "        \"serialGroupId\": \"serialGroupId\",\n" +
//                "        \"serialGroupName\": \"serialGroupName\",\n" +
//                "        \"access_token\": \"access_token\"\n" +
//                "      }\n" +
//                "    ],\n" +
//                "    \"partnerId\": \"partnerId\"\n" +
//                "  }\n" +
//                "}";
        String requestBody = "{\n" +
                "  \"url\": {\n" +
                "    \"host_port\": \"https://scrm-third-system-gateway-80-digital-ne-scrm-dev.cd-dev.nxengine.com/api/v1/lead/external/syncLead\",\n" +
                "    \"query_list\": [\n" +
                "      \n" +
                "    ]\n" +
                "  },\n" +
                "  \"header\": [\n" +
                "    \n" +
                "  ],\n" +
                "  \"method\": \"post\",\n" +
                "  \"body_format\": \"json\",\n" +
                "  \"body_ref\": [\n" +
                "    \n" +
                "  ],\n" +
                "  \"body\": {\n" +
                "    \"mediaLeadId\": \"mediaLeadId\",\n" +
                "    \"mediaCreateTime\": \"mediaCreateTime\",\n" +
                "    \"landingPageUrl\": \"landingPageUrl\",\n" +
                "    \"planId\": \"planId\",\n" +
                "    \"unitId\": \"unitId\",\n" +
                "    \"creativeId\": \"creativeId\",\n" +
                "    \"customerName\": \"customerName\",\n" +
                "    \"customerMobile\": \"customerMobile\",\n" +
                "    \"customerProvinceCode\": \"customerProvinceCode\",\n" +
                "    \"customerCityCode\": \"customerCityCode\",\n" +
                "    \"dealerCode\": \"dealerCode\",\n" +
                "    \"mediaLeadType\": \"mediaLeadType\",\n" +
                "    \"encryptFlag\": \"encryptFlag\",\n" +
                "    \"channelkey\": \"channelkey\",\n" +
                "    \"channelName\": \"channelName\",\n" +
                "    \"extendInfo\": {\n" +
                "      \"ucid\": \"ucid\"\n" +
                "    }\n" +
                "  }\n" +
                "}";



        JsonNode jsonNodeReq = JsonUtils.str2Obj(requestBody, JsonNode.class);


        JsonUtils.toArrayNode(jsonNodeReq.get("url").get("query_list")).add(JsonUtils.getMapper().readTree("{\"name\": \"access_token\",\"value\": \"access_token\",\"type\": \"variable\"}"));

//        T(com.baidu.ebiz.ldc.api.common.utils.JsonUtils).toArrayNode(#req.get("url").get("query_list")).add(T(com.baidu.ebiz.ldc.api.common.utils.JsonUtils).getMapper().readTree("{\"name\": \"access_token\",\"value\": \"access_token\",\"type\": \"variable\"}"))
//        JsonUtils.toArrayNode(jsonNodeReq.get("url").get("query_list")).add("aaa");

//        System.out.println(jsonNode.asText());
        System.out.println("query_list:" + JsonUtils.toArrayNode(jsonNodeReq.get("url").get("query_list")));

//        RequestModel requestModel = JsonUtils.str2Obj(jsonNodeReq.toString(), RequestModel.class);
//        URLModel url = requestModel.getUrl();
//        System.out.println("url:" + url);
//
//        JsonNode body = requestModel.getBody();
//        System.out.println("body:" + body);


//        System.out.println("jsonNode2=" +jsonNode2);
//        T(com.baidu.ebiz.ldc.api.common.utils.JsonUtils).toObjNode(#req.get("url")).get("query_list").add(T(com.baidu.ebiz.ldc.api.common.utils.JsonUtils).getMapper().readTree("{\"name\": \"access_token\",\"value\": \"access_token\",\"type\": \"variable\"}"))

        String response = "{\"code\":200,\"msg\":\"成功\",\"data\":{\"access_token\":\"cc31b95730f1410aaf4c91d110d4e059\",\"expire\":7200,\"expiretime\":1717829628571,\"generatetime\":1717822428571}}";



//        JsonNode jsonNode = JsonUtils.getMapper()
//                .readTree(response).get("data").get("access_token").asText();
//        System.out.println(jsonNode);
//        jsonNode.get("data")
//        ArrayNode arrayNode = JsonUtils.toArrayNode(jsonNode);
//
//        System.out.println(arrayNode);
//
//        JsonNode contentValueNode = arrayNode.get(0).get("contentValue");
////        System.out.println(contentValueNode);
//        String contentValue = arrayNode.get(0).get("contentValue").asText();
////        System.out.println(contentValue);
//        String contentValue2 = arrayNode.get(arrayNode.size() - 1).get("contentValue").asText();
//        JsonUtils.toObjNode(JsonUtils.toArrayNode(jsonNode).get(0)).put("contentKey", "王子晗");
//
//        System.out.println("JsonUtils.toArrayNode:" +JsonUtils.toArrayNode(null));
//        System.out.println((String) null);
//        System.out.println(arrayNode);
//
//        String str = null;
//        str.toString();

//        JsonNode jsonNode2 = JsonUtils.getMapper().readTree(additionalContent);
//        ArrayNode arrayNode = JsonUtils.toArrayNode(jsonNode2);
//
//        JsonNode contentValueNode = arrayNode.get(0).get("contentValue");
//        System.out.println(contentValueNode);
//        String contentValue = arrayNode.get(0).get("contentValue").asText();
//        System.out.println(contentValue);
//        String contentValue2 = arrayNode.get(arrayNode.size() - 1).get("contentValue").asText();
//        System.out.println(contentValue2);


    }

}
